/**
 * Created by sail on 2017/6/1.
 */
import WeCropper from '../../utils/cropper/we-cropper.js'
 
const app = getApp()
 
const device = wx.getSystemInfoSync()
const width = device.windowWidth
const height = app.globalData.windowHeight + 83 - 50
Page({
  data: {
    cropperOpt: {
      id: 'cropper',
      targetId: 'targetCropper',
      pixelRatio: device.pixelRatio,
      width,
      height,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 327) / 2,
        y: (height - 184) / 2,
        width: 327,
        height: 184
      },
      boundStyle: {
        color: "green",
        mask: 'rgba(0,0,0,0.8)',
        lineWidth: 1
      }
    }
  },
  touchStart(e) {
    this.cropper.touchStart(e)
  },
  touchMove(e) {
    this.cropper.touchMove(e)
  },
  touchEnd(e) {
    this.cropper.touchEnd(e)
  },
 
  //当点击生成图片按钮的时候，得到图片的src后，调用wx.uploadFile()上传图片，成功后可以再跳转到想要去的页面
  getCropperImage() {
    this.cropper.getCropperImage()
      .then((src) => {
        if(src.length<1) {
          throw new Error('未选择图片')
        } else {
          // console.log('src',src)
          app.globalData.curCover = src
          // app.globalData.updated = true
          wx.navigateBack({
            delta: 0,
          })
        }
      })
      .catch((err) => {
        wx.showModal({
          title: '温馨提示',
          content: err.message
        })
      })
  },
  uploadTap() {
    const self = this
    // console.log(this.data.cropperOpt.cut)
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        const src = res.tempFilePaths[0]
        //  获取裁剪图片资源后，给data添加src属性及其值
        console.log(src)
        self.cropper.pushOrign(src)
      }
    })
  },
  onLoad(option) {
    const { cropperOpt } = this.data

    console.log(height, device.windowHeight) 
    cropperOpt.boundStyle.color = "green"
 
    this.setData({ cropperOpt })
 
    this.cropper = new WeCropper(cropperOpt)
      .on('ready', (ctx) => {
        console.log(`wecropper is ready for work!`)
      })
      .on('beforeImageLoad', (ctx) => {
        wx.showToast({
          title: '上传中',
          icon: 'loading',
          duration: 2000
        })
      })
      .on('imageLoad', (ctx) => {
        wx.hideToast()
      })
  }
})